package com.jash.qiushi;

import android.content.Context;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jash.qiushi.entities.ItemEntity;
import com.jash.qiushi.entities.UserEntity;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> implements View.OnClickListener, IjkMediaPlayer.OnPreparedListener, IjkMediaPlayer.OnCompletionListener, IMediaPlayer.OnBufferingUpdateListener {
    private Context context;
    private List<ItemEntity> list;
    public static final String IMAGE_URL = "http://pic.qiushibaike.com/system/pictures/%s/%s/medium/%s";
    public static final String ICON_URL = "http://pic.qiushibaike.com/system/avtnew/%d/%d/thumb/%s";
    public static final String TAG = ItemAdapter.class.getSimpleName();
    private ViewHolder holder;
    private IjkMediaPlayer player;

    public ItemAdapter(Context context) {
        this.context = context;
        list = new ArrayList<>();
        player = new IjkMediaPlayer();
        player.setOnCompletionListener(this);
        player.setOnBufferingUpdateListener(this);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ViewHolder holder = new ViewHolder(LayoutInflater.from(context).inflate(viewType, parent, false));
        if (holder.video != null) {
            holder.video.setOnClickListener(this);
            holder.video.setTag(holder);
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ItemEntity item = list.get(position);
        if (item.getUser() != null) {
            holder.userInfo.setVisibility(View.VISIBLE);
            holder.userName.setText(item.getUser().getLogin());
            UserEntity user = item.getUser();
            String url = String.format(Locale.getDefault(), ICON_URL, user.getUid() / 10000, user.getUid(), user.getIcon());
            Picasso.with(context).load(url).transform(new CircleTransformation()).into(holder.userIcon);
        } else {
            holder.userInfo.setVisibility(View.GONE);
        }
        if (item.getImage() != null) {
            holder.image.setVisibility(View.VISIBLE);
            String image = item.getImage();
            Pattern pattern = Pattern.compile("(\\d+)\\d{4}");
            Matcher matcher = pattern.matcher(image);
            if (matcher.find()) {
                String url = String.format(Locale.getDefault(), IMAGE_URL, matcher.group(1), matcher.group(), image);
                Picasso.with(context).load(url).into(holder.image);
            }
        } else if (item.getPic_url() != null) {
            holder.image.setVisibility(View.VISIBLE);
            Picasso.with(context).load(item.getPic_url()).into(holder.image);
        } else {
            holder.image.setVisibility(View.GONE);
        }
        holder.content.setText(item.getContent());

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (list.get(position).getPic_url() == null) {
            return R.layout.item;
        } else {
            return R.layout.item_video;
        }
    }

    public void addAll(Collection<? extends ItemEntity> collection) {
        int size = list.size();
        list.addAll(collection);
        notifyItemRangeInserted(size, collection.size());
    }

    @Override
    public void onClick(View view) {
        if (holder == null || holder != view.getTag()) {
            if (holder != null) {
                holder.progress.setVisibility(View.INVISIBLE);
                holder.image.setVisibility(View.VISIBLE);
                holder.play.setVisibility(View.VISIBLE);
            }
            holder = ((ViewHolder) view.getTag());
            holder.play.setVisibility(View.INVISIBLE);
            holder.progress.setVisibility(View.VISIBLE);
            player.setDisplay(holder.video.getHolder());
            player.reset();
            int position = holder.getAdapterPosition();
            try {
                player.setDataSource(list.get(position).getLow_url());
                player.setOnPreparedListener(this);
                player.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if (player.isPlaying()) {
                player.pause();
                holder.play.setVisibility(View.VISIBLE);
            } else {
                player.start();
                holder.play.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    public void onPrepared(IMediaPlayer mediaPlayer) {
        player.start();
        holder.image.setVisibility(View.INVISIBLE);
        holder.progress.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onViewDetachedFromWindow(ViewHolder holder) {
        if (this.holder == holder) {
            player.stop();
            holder.play.setVisibility(View.VISIBLE);
            holder.image.setVisibility(View.VISIBLE);
            holder.progress.setVisibility(View.INVISIBLE);
            this.holder = null;
        }
    }

    @Override
    public void onCompletion(IMediaPlayer mediaPlayer) {
        holder.play.setVisibility(View.VISIBLE);
        holder.image.setVisibility(View.VISIBLE);
        holder.progress.setVisibility(View.INVISIBLE);
        holder = null;
    }

    @Override
    public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i) {
        Log.d(TAG, "onBufferingUpdate: " + i);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView userIcon;
        private TextView userName;
        private LinearLayout userInfo;
        private TextView content;
        private ImageView image;
        private SurfaceView video;
        private ImageView play;
        private ProgressBar progress;

        public ViewHolder(View itemView) {
            super(itemView);
            userIcon = ((ImageView) itemView.findViewById(R.id.user_icon));
            userName = ((TextView) itemView.findViewById(R.id.user_name));
            userInfo = ((LinearLayout) itemView.findViewById(R.id.user_info));
            content = ((TextView) itemView.findViewById(R.id.item_content));
            image = ((ImageView) itemView.findViewById(R.id.item_image));
            video = ((SurfaceView) itemView.findViewById(R.id.item_video));
            play = ((ImageView) itemView.findViewById(R.id.item_play));
            progress = ((ProgressBar) itemView.findViewById(R.id.item_progress));
        }
    }
}
